package org.ww.ucenter.controller;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.ww.commonutils.JwtUtils;
import org.ww.servicebase.exceptionhandler.GuliException;
import org.ww.ucenter.bean.Member;
import org.ww.ucenter.bean.vo.MemberVo;
import org.ww.ucenter.service.MemberService;
import org.ww.ucenter.utils.ConstantsWxUtil;
import org.ww.ucenter.utils.HttpClientUtils;

import java.net.URLEncoder;
import java.util.HashMap;

@Controller
@RequestMapping("/api/ucenter/wx")
//@CrossOrigin
public class WxApiController {

    @Autowired
    private MemberService memberService;

    //2 开发回调URL
    @GetMapping("/callback")
    public String callback(String code,String state){
        
        try{
            //1 获取code值，临时票据，类似于验证码

            //2 拿着code请求微信固定的地址，得到两个值accsess_token 和 openid
            String baseAccessTokenUrl="https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";

            //拼接三个参数：id 密钥 和 code值
            String accessTokenUrl=String.format(
                    baseAccessTokenUrl,
                    ConstantsWxUtil.WX_OPEN_APP_ID,
                    ConstantsWxUtil.WX_OPEN_APP_SECRET,
                    code
            );
            //请求这个拼接好的地址得到两个值，accsess_token 和 openid
            //使用httpclient发送请求，得到结果
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);

            //从accessTokenInfo里边获取两个值access_token和openid
            //把accessTokenInfo转换成map集合，根据map里的key获取具体的值
            //使用json转换工具gson
            Gson gson=new Gson();
            HashMap accessTokenMap = gson.fromJson(accessTokenInfo, HashMap.class);
            String accessToken =(String) accessTokenMap.get("access_token");
            String openid =(String) accessTokenMap.get("openid");


            //根据openid查询是否存在该用户信息
            Member member=memberService.getByOpenid(openid);
            if(member==null){
                //3 根据得到的两个值access_token和openid接着访问固定的地址
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        accessToken,
                        openid);
                //通过httpclient发送请求，获取用户信息
                String userInfo = HttpClientUtils.get(userInfoUrl);
                //将用户信息通过gson转换map
                HashMap userMap = gson.fromJson(userInfo, HashMap.class);
                //获取用户昵称和头像
                String nickname =(String) userMap.get("nickname");
                String headimgurl =(String) userMap.get("headimgurl");


                //将用户信息存入到数据库中
                member=new Member();
                member.setOpenid(openid);
                member.setAvatar(headimgurl);
                member.setNickname(nickname);
                memberService.save(member);
            }

            //使用jwt生成token
            String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            return "redirect:http://localhost:3000?token="+token;

        }catch (Exception e){
            throw new GuliException(20001,"登陆失败");
        }

    }

    //1 生成微信二维码
    @GetMapping("/getWxCode")
    public String getWxCode(){
        String baseUrl="https://open.weixin.qq.com/connect/qrconnect"+
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        String redirectUrl=ConstantsWxUtil.WX_OPEN_REDIRECT_URL;//获取业务服务器重定向地址
        try{
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8");
        }catch (Exception e){
            throw new GuliException(20001,e.getMessage());
        }

        String url=String.format(
                baseUrl,
                ConstantsWxUtil.WX_OPEN_APP_ID,
                redirectUrl,
                "kk"
        );
        return "redirect:"+url;

    }
}
